package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.http.RankMoreCategoryParser.RankMoreCategory;
import com.myapp.ruyixing.model.RankCategory.RankSubCategory;

public class RankMoreMenuFragment extends ListFragment implements
		OnItemClickListener {

	private RankMoreCategory mRankMoreCategory;

	private RYHttpResponseHandler mCategoryHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			mRankMoreCategory = (RankMoreCategory) o;

			if (mRankMoreCategory != null && mRankMoreCategory.data != null) {
				List<RankSubCategory> list = new ArrayList<RankSubCategory>(
						mRankMoreCategory.data);
				for (RankSubCategory subCategory : list) {
					if ("热门商家".equals(subCategory.name)
							|| "最佳商户".equals(subCategory.name)
							|| "服务最佳".equals(subCategory.name)) {
						mRankMoreCategory.data.remove(subCategory);
					}
				}
				String[] items = new String[mRankMoreCategory.data.size()];
				int i = 0;
				for (RankSubCategory subCategory : mRankMoreCategory.data) {
					items[i++] = subCategory.name;
				}
				setListAdapter(new ArrayAdapter<String>(getActivity(),
						android.R.layout.simple_list_item_1, items));
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
		}
	};

	public static RankMoreMenuFragment getInstance(String typeid) {
		RankMoreMenuFragment fragment = new RankMoreMenuFragment();
		Bundle bundle = new Bundle();
		bundle.putString("typeid", typeid);
		fragment.setArguments(bundle);

		return fragment;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		getListView().setOnItemClickListener(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		String typeid = getArguments().getString("typeid");
		RYHttpClient.getRankMoreCategory(getActivity(), mCategoryHandler,
				typeid);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		((RankActivity) getActivity()).changeSubType(
				mRankMoreCategory.data.get(position).id,
				mRankMoreCategory.data.get(position).name);
	}
}
